/*
*  Copyright (c) 2001 Sun Microsystems, Inc.  All rights
*  reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*  1. Redistributions of source code must retain the above copyright
*  notice, this list of conditions and the following disclaimer.
*
*  2. Redistributions in binary form must reproduce the above copyright
*  notice, this list of conditions and the following disclaimer in
*  the documentation and/or other materials provided with the
*  distribution.
*
*  3. The end-user documentation included with the redistribution,
*  if any, must include the following acknowledgment:
*  "This product includes software developed by the
*  Sun Microsystems, Inc. for Project JXTA."
*  Alternately, this acknowledgment may appear in the software itself,
*  if and wherever such third-party acknowledgments normally appear.
*
*  4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
*  must not be used to endorse or promote products derived from this
*  software without prior written permission. For written
*  permission, please contact Project JXTA at http://www.jxta.org.
*
*  5. Products derived from this software may not be called "JXTA",
*  nor may "JXTA" appear in their name, without prior written
*  permission of Sun.
*
*  THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
*  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*  DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
*  ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
*  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
*  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
*  USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
*  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
*  OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
*  OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*  SUCH DAMAGE.
*  ====================================================================
*
*  This software consists of voluntary contributions made by many
*  individuals on behalf of Project JXTA.  For more
*  information on Project JXTA, please see
*  <http://www.jxta.org/>.
*
*  This license is based on the BSD license adopted by the Apache Foundation.
*
*  $Id: LDAPAuthenticator.java,v 1.5 2006/07/13 05:26:40 nano Exp $
*/

package net.jxta.myjxta.util;


import net.jxta.ext.config.ResourceManager;
import net.jxta.myjxta.misc.unused.Authenticator;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.*;
import java.text.MessageFormat;
import java.util.Hashtable;

/**
 *
 * @version $Id: LDAPAuthenticator.java,v 1.5 2006/07/13 05:26:40 nano Exp $
 *
 * @author james todd [gonzo at jxta dot org]
 */

public class LDAPAuthenticator
    extends Authenticator {

    public static final String APPLICATION_AUTHENTICATOR_LDAP =
        APPLICATION_AUTHENTICATOR + "/ldap";
    public static final String APPLICATION_AUTHENTICATOR_LDAP_CONTEXT =
        APPLICATION_AUTHENTICATOR_LDAP + "/@context";
    public static final String APPLICATION_AUTHENTICATOR_LDAP_CONTEXT_DEFAULT =
        "com.sun.jndi.ldap.LdapCtxFactory";
    public static final String APPLICATION_AUTHENTICATOR_LDAP_URL =
        APPLICATION_AUTHENTICATOR_LDAP + "/@url";
    public static final String APPLICATION_AUTHENTICATOR_LDAP_AUTHENTICATION =
        APPLICATION_AUTHENTICATOR_LDAP + "/@authentication";
    public static final String APPLICATION_AUTHENTICATOR_LDAP_PRINCIPAL =
        APPLICATION_AUTHENTICATOR_LDAP + "/principal";
    public static final String APPLICATION_AUTHENTICATOR_LDAP_PRINCIPAL_NAME =
        APPLICATION_AUTHENTICATOR_LDAP_PRINCIPAL + "/@name";
    public static final String APPLICATION_AUTHENTICATOR_LDAP_SEARCH =
        APPLICATION_AUTHENTICATOR_LDAP + "/search";
    public static final String APPLICATION_AUTHENTICATOR_LDAP_SEARCH_NAME =
        APPLICATION_AUTHENTICATOR_LDAP_SEARCH + "/@name";
    public static final String APPLICATION_AUTHENTICATOR_LDAP_SEARCH_FILTER =
        APPLICATION_AUTHENTICATOR_LDAP_SEARCH + "/@filter";
    public static final String APPLICATION_AUTHENTICATOR_LDAP_SEARCH_ATTRIBUTE =
        APPLICATION_AUTHENTICATOR_LDAP_SEARCH + "/@attribute";

    private String context = null;
    private String url = null;
    private String authentication = null;
    private String principalName = null;
    private String searchName = null;
    private String searchFilter = null;
    private String searchAttribute = null;

    public String getPrincipal() {
        String principal = System.getProperty("user.name");

        return principal;
    }

    public String getId() {
        String id = getId(getPrincipal());

        return id;
    }

    public String getId(String principal) {
        String id = null;
        Hashtable env = getDirEnv();

        if (env != null) {
            DirContext context = null;
            SearchControls constraints = new SearchControls();
            String s = null;

            try {
                s = MessageFormat.format(this.searchFilter,
                                         new Object[] { principal });
            } catch (Exception e) {
            }

            constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);

            try {
                context = new InitialDirContext(env);

                for (NamingEnumeration results =
                            context.search(this.searchName, s, constraints);
                        results.hasMore(); ) {
                    SearchResult result = (SearchResult)results.next();
                    Attributes attributes = result.getAttributes();

                    if (attributes != null) {
                        try {
                            id = (String)attributes.get(this.searchAttribute).get();
                        } catch (ClassCastException cce) {
                        }
                    }
                }
            } catch (NamingException ne) {
            } finally {
                if (context != null) {
                    try {
                        context.close();
                    } catch (NamingException ne) {
                    }
                }
            }
        }

        return id;
    }

    public boolean authenticate(String credentials) {
        boolean isAuthenticated = authenticate(getPrincipal(), credentials);

        return isAuthenticated;
    }

    public boolean authenticate(String principal, String credentials) {
        boolean isValid = false;
        String p = getPrincipal();

        isValid = (p != null &&
                   principal != null); // &&
        //                   p.equals(principal));

        boolean isAuthenticated = isValid &&
                                  validate(getId(principal), credentials);

        return isAuthenticated;
    }

    protected void process(ResourceManager resources)
    throws IllegalArgumentException {
        try {
            super.process(resources);
        } catch (IllegalArgumentException iae) {
        }

        this.context = resources.get(APPLICATION_AUTHENTICATOR_LDAP_CONTEXT,
            Prefs.Default.LDAP_CONTEXT);
        this.url = resources.get(APPLICATION_AUTHENTICATOR_LDAP_URL,
            Prefs.Default.LDAP_URL);
        this.authentication =
            resources.get(APPLICATION_AUTHENTICATOR_LDAP_AUTHENTICATION,
                Prefs.Default.LDAP_AUTHENTICATION);
        this.principalName =
            resources.get(APPLICATION_AUTHENTICATOR_LDAP_PRINCIPAL_NAME,
                Prefs.Default.LDAP_PRINCIPAL);
        this.searchName =
            resources.get(APPLICATION_AUTHENTICATOR_LDAP_SEARCH_NAME,
                Prefs.Default.LDAP_SEARCH_NAME);
        this.searchFilter =
            resources.get(APPLICATION_AUTHENTICATOR_LDAP_SEARCH_FILTER,
                Prefs.Default.LDAP_SEARCH_FILTER);
        this.searchAttribute =
            resources.get(APPLICATION_AUTHENTICATOR_LDAP_SEARCH_ATTRIBUTE,
                Prefs.Default.LDAP_SEARCH_ATTRIBUTE);

        if (getName() == null ||
                this.context == null ||
                this.url == null ||
                this.authentication == null ||
                this.principalName == null ||
                this.searchName == null ||
                this.searchFilter == null ||
                this.searchAttribute == null) {
            String msg = "bad configuration: " +
                         "\n  name             : " + getName() +
                         "\n  context          : " + this.context +
                         "\n  url              : " + this.url +
                         "\n  authentication   : " + this.authentication +
                         "\n  principal name   : " + this.principalName +
                         "\n  search name      : " + this.searchName +
                         "\n  search filter    : " + this.searchFilter +
                         "\n  search attribute : " + this.searchAttribute;
            IllegalArgumentException iae = new IllegalArgumentException(msg);

            throw iae;
        }

        // todo: persist preferneces
//        prefs.put(Prefs.AUTHENTICATOR_CLASS, getName());
//        prefs.put(Prefs.LDAP_CONTEXT, this.context);
//        prefs.put(Prefs.LDAP_URL, this.url);
//        prefs.put(Prefs.LDAP_AUTHENTICATION, this.authentication);
//        prefs.put(Prefs.LDAP_PRINCIPAL, this.principalName);
//        prefs.put(Prefs.LDAP_SEARCH_NAME, this.searchName);
//        prefs.put(Prefs.LDAP_SEARCH_FILTER, this.searchFilter);
//        prefs.put(Prefs.LDAP_SEARCH_ATTRIBUTE, this.searchAttribute);
    }

    private boolean validate(String principal, String credentials) {
        boolean status = false;

        if (principal != null &&
                credentials != null) {
            Hashtable env = getDirEnv(principal, credentials);

            if (env != null) {
                DirContext context = null;

                try {
                    context = new InitialDirContext(env);

                    status = true;
                } catch (NamingException ne) {
                } finally {
                    if (context != null) {
                        try {
                            context.close();
                        } catch (NamingException ne) {
                        }
                    }
                }
            }
        }

        return status;
    }

    private Hashtable getDirEnv() {
        return getDirEnv(null, null);
    }

    private Hashtable getDirEnv(String principal, String credentials) {
        Hashtable<String, String> env = new Hashtable();

        env.put(Context.INITIAL_CONTEXT_FACTORY, this.context);
        env.put(Context.PROVIDER_URL, this.url);

        if (principal != null &&
                credentials != null) {
            String s = null;

            try {
                s = MessageFormat.format(this.principalName,
                                         new Object[] { principal });
            } catch (Exception e) {
            }

            if (s != null) {
                env.put(Context.SECURITY_AUTHENTICATION,
                        this.authentication);
                env.put(Context.SECURITY_PRINCIPAL, s);
                env.put(Context.SECURITY_CREDENTIALS, credentials);
            } else {
                env = null;
            }
        }

        return env;
    }

    private String mask(String s) {
        StringBuffer sb = new StringBuffer();
        final String mask = "*";

        if (s != null) {
            for (int i = 0; i < s.length(); i++) {
                sb.append(mask);
            }
        }

        return sb.toString();
    }
}
